//
//  SingleChoicePickerView.swift
//  单选弹窗选择 View
//
//  Created by 千策万划-mini on 2025/5/6.
//

import Foundation

class SingleChoicePickerView: UIView, UIPickerViewDataSource, UIPickerViewDelegate {

    var blockConfirmClick: ((String, String) -> Void)?
    var modelDetail: ModelAuthPersonalItemInfo = .init()
    var selectValue: String = ""
    var selectCode: String = ""
    var temporaryValue: String = ""
    var temporaryCode:  String = ""
    var titleStr: String = ""
    var subTitleStr: String = ""
    var isShowImage: Bool = false

    // MARK: - lazy
    lazy var imageBack: UIImageView = {
        let result = UIImageView()
        result.isUserInteractionEnabled = true
        result.widthHeight = XY(W(355), W(508))
        result.image = UIImage(named: "icon_idcard_example_bg")
        return result
    }()

    lazy var btnClose: UIButton = {
        let result = UIButton()
        result.widthHeight = XY(40 + 16 * 2, 40 + 30 * 2)
        result.tag = 1
        result.addTarget(self, action: #selector(btnClick(_:)), for: .touchUpInside)
        return result
    }()

    lazy var labelTitle: OutlineLabel = {
        let result = OutlineLabel()
        return result
    }()

    lazy var labelSubTitle: OutlineLabel = {
        let result = OutlineLabel()
        return result
    }()

    lazy var imageContent: UIImageView = {
        let result = UIImageView()
        result.isUserInteractionEnabled = true
        result.widthHeight = XY(W(275), W(290))
        result.image = UIImage(named: "icon_login_input_bg")
        return result
    }()

    lazy var btnConfirm: UIButton = {
        let result = UIButton()
        result.widthHeight = XY(W(168), W(46))
        result.setBackgroundImage(UIImage(named: "icon_pop_cancel"), for: .normal)
        result.tag = 2
        result.addTarget(self, action: #selector(btnClick(_:)), for: .touchUpInside)
        let label = OutlineLabel()
        label.resetView(
            title: "Confirming",
            textColor: COLOR_WHITE(),
            font: UIFont.customBoldFont(size: 16),
            shadowColor: UIColor(hex: "#1B4506"),
            outlineColor: UIColor(hex: "#004600")
        )
        label.centerXCenterY = XY(result.width / 2, result.height / 2)
        result.addSubview(label)
        return result
    }()

    lazy var pickerView: UIPickerView = {
        let result = UIPickerView()
        result.dataSource = self
        result.delegate = self
        return result
    }()

    lazy var imagePickerIndicator: UIImageView = {
        let result = UIImageView()
        result.isUserInteractionEnabled = false
        result.image = UIImage(named: "icon_login_tf_bg")
        return result
    }()

    // MARK: - init
    override init(frame: CGRect) {
        super.init(frame: frame)
        widthHeight = XY(SCREEN_WIDTH, SCREEN_HEIGHT)
        backgroundColor = UIColor(hex: "000000", alpha: 0.8)
        addSubView()
    }

    @available(*, unavailable)
    required init?(coder _: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        for subview in pickerView.subviews {
            subview.backgroundColor = .clear
        }
    }

    // MARK: - 添加
    func addSubView() {
        addSubview(imageBack)
        imageBack.addSubview(labelTitle)
        imageBack.addSubview(labelSubTitle)
        imageBack.addSubview(imageContent)
        imageBack.addSubview(btnClose)
        imageBack.addSubview(btnConfirm)
        imageContent.addSubview(imagePickerIndicator)
        imageContent.addSubview(pickerView)
        resetView()
    }

    // MARK: - 点击事件
    @objc func btnClick(_ sender: UIControl) {
        feedback()
        sender.addClickAnimate()
        switch sender.tag {
        case 1:
            hide()
        case 2:
            selectValue = temporaryValue
            selectCode  = temporaryCode
            if let block = blockConfirmClick {
                block(selectValue, selectCode)
            }
            hide()
        default:
            break
        }
    }

    // 显示
    func show() {
        if let window = WindowManager.shared.getCurrentWindow() {
            window.endEditing(true)
            // 设置初始状态（比如从底部开始）
            alpha = 0
            imageBack.transform = CGAffineTransform(translationX: 0, y: 50)
            window.addSubview(self)
            // 添加弹出动画
            UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseOut) {
                self.alpha = 1
                self.imageBack.transform = .identity
            }
        }
    }

    // 隐藏
    func hide() {
        // 添加消失动画
        UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseIn) {
            self.alpha = 0
            self.imageBack.transform = CGAffineTransform(translationX: 0, y: 50)
        } completion: { _ in
            self.removeFromSuperview()
            // 重置 transform，以便下次显示
            self.imageBack.transform = .identity
        }
    }

    // MARK: - UIPickerView
    func numberOfComponents(in _: UIPickerView) -> Int {
        return 1
    }

    func pickerView(_: UIPickerView, numberOfRowsInComponent _: Int) -> Int {
        return modelDetail.ages.count
    }

    func pickerView(_: UIPickerView, rowHeightForComponent _: Int) -> CGFloat {
        return 60
    }

    func pickerView(_: UIPickerView, viewForRow row: Int, forComponent _: Int, reusing view: UIView?) -> UIView {
        isShowImage = isStr(modelDetail.ages[row].daydfdgd)
        if isShowImage {
            // 显示 logo
            let view = UIView()
            view.widthHeight = XY(pickerView.width-20, 60)
            view.centerXTop = XY(pickerView.width/2, 0)
            
            let imageLogo = UIImageView()
            imageLogo.widthHeight = XY(W(28), W(28))
            imageLogo.contentMode = .scaleAspectFill;
            imageLogo.clipsToBounds = true;
            imageLogo.setImage(urlStr: modelDetail.ages[row].daydfdgd)
            view.addSubview(imageLogo)
            
            let customLabel = (view as? UILabel) ?? {
                let label = UILabel()
                label.textAlignment = .center
                label.font = UIFont.customBoldFont(size: 16)
                label.textColor = UIColor(hex: "#5228D7")
                return label
            }()
            customLabel.fitTitle(modelDetail.ages[row].cautiously, variable: 0)
            customLabel.textColor = UIColor(hex: "#5228D7")
            view.addSubview(customLabel)
            
            imageLogo.leftCenterY = XY((view.width-customLabel.width-5-imageLogo.width)/2, view.height/2)
            customLabel.leftCenterY = XY(imageLogo.right+5, imageLogo.centerY)
            
            return view
        }else{
            // 不显示图片，只显示文字
            let customLabel = (view as? UILabel) ?? {
                let label = UILabel()
                label.textAlignment = .center
                label.font = UIFont.customBoldFont(size: 16)
                label.textColor = UIColor(hex: "#5228D7")
                return label
            }()
            customLabel.text = modelDetail.ages[row].cautiously
            customLabel.textColor = UIColor(hex: "#5228D7")
            return customLabel
        }
    }

    func pickerView(_: UIPickerView, titleForRow row: Int, forComponent _: Int) -> String? {
        return modelDetail.ages[row].cautiously
    }

    func pickerView(_: UIPickerView, didSelectRow row: Int, inComponent _: Int) {
        temporaryValue = modelDetail.ages[row].cautiously
        temporaryCode = "\(modelDetail.ages[row].wisest)"
    }

    // MARK: - 重置界面
    func resetView(model: ModelAuthPersonalItemInfo = ModelAuthPersonalItemInfo()) {
        modelDetail = model
        if !isStr(selectValue) {
            let modelBtn = model.ages.first
            selectValue = modelBtn?.cautiously ?? ""
            selectCode = UnPackStr(modelBtn?.wisest)
            temporaryValue = selectValue
            temporaryCode  = selectCode
        }
        imageBack.centerXCenterY = XY(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2)
        btnClose.rightTop = XY(imageBack.width, 0)

        labelSubTitle.isHidden = !isStr(subTitleStr)
        if isStr(titleStr) {
            labelTitle.resetView(
                title: titleStr,
                textColor: COLOR_WHITE(),
                font: UIFont.customBoldFont(size: 24),
                shadowColor: UIColor(hex: "#4105A0"),
                outlineColor: UIColor(hex: "#3B0B9A")
            )
        }
//        if isStr(subTitleStr){
        labelTitle.centerXTop = XY(imageBack.width / 2, W(26))
//        }else{
//            labelTitle.centerXTop = XY(imageBack.width/2, W(16))
//            labelSubTitle.centerXTop = XY(imageBack.width/2, labelTitle.bottom-W(17))
//        }

        imageContent.centerXTop = XY(imageBack.width / 2, W(126))

        pickerView.widthHeight = XY(imageContent.width - W(10) * 2, imageContent.height - W(20) * 2)
        pickerView.centerXCenterY = XY(imageContent.width / 2, imageContent.height / 2)
        pickerView.backgroundColor = .clear
        for subview in pickerView.subviews {
            subview.backgroundColor = .clear
        }

        imagePickerIndicator.widthHeight = XY(imageContent.width - 10 * 2, 60)
        imagePickerIndicator.centerXCenterY = XY(imageContent.width / 2, imageContent.height / 2)

        if isStr(selectValue) {
            // 遍历查找对应的索引
            for (index, item) in model.ages.enumerated() {
                if item.cautiously == selectValue {
                    // 滚动到对应的行
                    pickerView.selectRow(index, inComponent: 0, animated: false)
                    break
                }
            }
        }

        btnConfirm.centerXTop = XY(imageBack.width / 2, imageContent.bottom + W(15))
    }
}
